package com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.repository.HddcB1PaleoeqeventNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.repository.HddcB1PaleoeqeventRepository;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.repository.entity.HddcB1PaleoeqeventEntity;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.service.HddcB1PaleoeqeventService;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.viewobjects.HddcB1PaleoeqeventPageVO;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.viewobjects.HddcB1PaleoeqeventQueryParams;
import com.css.zfzx.sjcj.modules.hddcB1PaleoEQEvent.viewobjects.HddcB1PaleoeqeventVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地质调查数据-探槽古地震事件-属性表管理
 *
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB1PaleoeqeventServiceImpl implements HddcB1PaleoeqeventService {

    private final HddcB1PaleoeqeventRepository hddcB1PaleoeqeventRepository;
    private final HddcB1PaleoeqeventNativeRepository hddcB1PaleoeqeventNativeRepository;
    private final TrialTrenchTheAncientEarthquakeExcelVerifyHandler trialTrenchTheAncientEarthquakeExcelVerifyHandler;

    @Autowired
    public HddcB1PaleoeqeventServiceImpl(HddcB1PaleoeqeventRepository hddcB1PaleoeqeventRepository,
                                         HddcB1PaleoeqeventNativeRepository hddcB1PaleoeqeventNativeRepository,
                                         TrialTrenchTheAncientEarthquakeExcelVerifyHandler trialTrenchTheAncientEarthquakeExcelVerifyHandler) {
        this.hddcB1PaleoeqeventRepository = hddcB1PaleoeqeventRepository;
        this.hddcB1PaleoeqeventNativeRepository = hddcB1PaleoeqeventNativeRepository;
        this.trialTrenchTheAncientEarthquakeExcelVerifyHandler = trialTrenchTheAncientEarthquakeExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB1Paleoeqevents(HddcB1PaleoeqeventQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB1PaleoeqeventPageVO> hddcB1PaleoeqeventPage = this.hddcB1PaleoeqeventNativeRepository.queryHddcB1Paleoeqevents(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB1PaleoeqeventPage);
    }

    @Override
    public HddcB1PaleoeqeventEntity getHddcB1Paleoeqevent(String id) {
        return this.hddcB1PaleoeqeventRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1PaleoeqeventEntity saveHddcB1Paleoeqevent(HddcB1PaleoeqeventEntity hddcB1Paleoeqevent) {
        hddcB1Paleoeqevent.setUuid(UUIDGenerator.getUUID());
        hddcB1Paleoeqevent.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB1Paleoeqevent.setCreateTime(now);
        hddcB1Paleoeqevent.setUpdateTime(now);
        hddcB1Paleoeqevent.setIsValid(PlatformConstants.Y);
        hddcB1Paleoeqevent.setQualityinspectionStatus(PlatformConstants.N);
        hddcB1Paleoeqevent.setExtends10(PlatformConstants.Y);
        this.hddcB1PaleoeqeventRepository.save(hddcB1Paleoeqevent);
        return hddcB1Paleoeqevent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1PaleoeqeventEntity updateHddcB1Paleoeqevent(HddcB1PaleoeqeventEntity hddcB1Paleoeqevent) {
        HddcB1PaleoeqeventEntity entity = hddcB1PaleoeqeventRepository.findById(hddcB1Paleoeqevent.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcB1Paleoeqevent);
        hddcB1Paleoeqevent.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB1Paleoeqevent.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB1PaleoeqeventRepository.save(hddcB1Paleoeqevent);
        return hddcB1Paleoeqevent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB1Paleoeqevents(List<String> ids) {
        List<HddcB1PaleoeqeventEntity> hddcB1PaleoeqeventList = this.hddcB1PaleoeqeventRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB1PaleoeqeventList) && hddcB1PaleoeqeventList.size() > 0) {
            for (HddcB1PaleoeqeventEntity hddcB1Paleoeqevent : hddcB1PaleoeqeventList) {
//                this.hddcB1PaleoeqeventRepository.delete(hddcB1Paleoeqevent);
                hddcB1Paleoeqevent.setIsValid("0");
                hddcB1Paleoeqevent.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB1Paleoeqevent.setUpdateTime(new Date());
                this.hddcB1PaleoeqeventRepository.save(hddcB1Paleoeqevent);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB1PaleoeqeventQueryParams queryParams, HttpServletResponse response) {
        List<HddcB1PaleoeqeventEntity> yhDisasterEntities = hddcB1PaleoeqeventNativeRepository.exportYhDisasters(queryParams);
        List<HddcB1PaleoeqeventVO> list = new ArrayList<>();
        for (HddcB1PaleoeqeventEntity entity : yhDisasterEntities) {
            HddcB1PaleoeqeventVO yhDisasterVO = new HddcB1PaleoeqeventVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "探槽古地震事件", "探槽古地震事件", HddcB1PaleoeqeventVO.class, "探槽古地震事件.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(trialTrenchTheAncientEarthquakeExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB1PaleoeqeventVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB1PaleoeqeventVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB1PaleoeqeventVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB1PaleoeqeventVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB1PaleoeqeventVO> list) {
        for (HddcB1PaleoeqeventVO hddcB1PaleoeqeventVO : list) {
            HddcB1PaleoeqeventEntity yhDisasterEntity = new HddcB1PaleoeqeventEntity();
            BeanUtils.copyProperties(hddcB1PaleoeqeventVO, yhDisasterEntity);
            saveHddcB1Paleoeqevent(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB1PaleoeqeventEntity> hddcDataList = this.hddcB1PaleoeqeventRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB1PaleoeqeventEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB1PaleoeqeventRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB1PaleoeqeventEntity> hddcDataList = this.hddcB1PaleoeqeventRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB1PaleoeqeventEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB1PaleoeqeventRepository.save(entity);
            }
        }
    }

}
